//
//  PeopleDetailViewController.m
//  jungoo
//
//  Created by Sinbad Fly on 8/30/12.
//  Copyright (c) 2012 ABOM. All rights reserved.
//

#import "PeopleDetailViewController.h"
#import "Extensions.h"

@implementation PeopleDetailViewController

@synthesize peopleInfo = _peopleInfo, peopleSetting = _peopleSetting, publicInfomation = _publicInfomation, peoplePhotos = _peoplePhotos;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - Private Method

- (UITableViewCell*)createFromNibForCell1
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"PeopleDetailCell" 
                                                   owner:nil 
                                                 options:nil];
    
    return (id)[views objectAtIndex:0];
}

- (UITableViewCell*)createFromNibForCell2
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"PeopleDetailCell" 
                                                   owner:nil 
                                                 options:nil];
    
    return (id)[views objectAtIndex:1];    
}

- (UITableViewCell*)createFromNibForCell3
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"PeopleDetailCell" 
                                                   owner:nil 
                                                 options:nil];
    
    return (id)[views objectAtIndex:2];    
}

- (UITableViewCell*)createFromNibForCell4
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"PeopleDetailCell" 
                                                   owner:nil 
                                                 options:nil];
    
    return (id)[views objectAtIndex:3];    
}

- (void)applyAppearance
{
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back)];   
    
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]];    
    [self.tableView setBackgroundView:nil];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self setTitle:@"People Profile"];
}

- (void)sizeToFitForCell:(UITableViewCell*)cell
{
    CGFloat wTitle = 0;
    CGRect newRect = CGRectZero;
    UILabel *titleUI = [cell titleTextWithTag:1];
    UILabel *contentUI = [cell titleTextWithTag:2];                  
            
    wTitle = [JGoUtility widthFromString:titleUI.text font:titleUI.font];
    newRect = titleUI.frame;
    newRect.size.width = wTitle;
    [cell titleTextWithTag:1].frame = newRect; 
    
    newRect = contentUI.frame;
    wTitle = [JGoUtility widthFromString:contentUI.text font:contentUI.font];
    newRect.origin.x = titleUI.frame.origin.x + titleUI.frame.size.width + 2;
    newRect.size.width = wTitle;
    
    if (newRect.origin.x + newRect.size.width > 300) {
        
    }
    
    contentUI.frame = newRect;
}

- (NSDictionary*)parsingSetting
{
    NSDictionary *settings = [_peopleInfo objectForKey:@"setting"];
    NSMutableDictionary *parsedSetting = [[NSMutableDictionary new] autorelease];
    
    [parsedSetting setValue:@"1" forKey:@"status"];
    [parsedSetting setValue:@"1" forKey:@"course"];
    [parsedSetting setValue:@"1" forKey:@"u_year"];
    [parsedSetting setValue:@"1" forKey:@"modules"];
    [parsedSetting setValue:@"1" forKey:@"college"]; 
    
    if ([settings isKindOfClass:[NSDictionary class]]) {
        for (NSString *key in [settings allKeys]) {   
            NSString *value = [settings objectForKey:key];
            [parsedSetting setValue:value forKey:key];                
        }
    }

    return parsedSetting;
}

- (void)countPublicInformation
{
    _publicInfomation = [NSMutableArray new]; 
    NSDictionary *dictionaryTmp = nil;  
    
    if ([[_peopleSetting objectForKey:@"course"] integerValue] == 1) {
        dictionaryTmp = [NSDictionary dictionaryWithObject:[_peopleInfo objectForKey:@"course"]
                                                    forKey:@"Course: "];
        [_publicInfomation addObject:dictionaryTmp];
    }
    
    if ([[_peopleSetting objectForKey:@"u_year"] integerValue] == 1) {
        dictionaryTmp = [NSDictionary dictionaryWithObject:[_peopleInfo objectForKey:@"u_year"]
                                                    forKey:@"Class: "];
        [_publicInfomation addObject:dictionaryTmp];
    }
    
    if ([[_peopleSetting objectForKey:@"modules"] integerValue] == 1) {
        NSString *modulesString = [JGoUtility stringFromArray:[_peopleInfo objectForKey:@"modules"]];
        dictionaryTmp = [NSDictionary dictionaryWithObject:modulesString
                                                    forKey:@"Modules: "];
        [_publicInfomation addObject:dictionaryTmp];
    }
    
    if ([[_peopleSetting objectForKey:@"college"] integerValue] == 1) {
        dictionaryTmp = [NSDictionary dictionaryWithObject:[_peopleInfo objectForKey:@"college"]
                                                    forKey:@"School: "];
        [_publicInfomation addObject:dictionaryTmp];
    }
    
    if ([_publicInfomation count] == 0) {
        [_publicInfomation release];
        _publicInfomation = nil;
    }       
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self applyAppearance];        
    _peopleSetting = [[self parsingSetting] retain];
    [self countPublicInformation];
    
    [JGoUtility showProgressInView:self.view 
                            target:self title:@"Loading..." 
                          selector:@selector(delayLoadPeoplePhoto:)];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)dealloc
{
    [self setTableView:nil];
    [self setPeopleInfo:nil];
    [_peopleSetting release];
    [_publicInfomation release];
    [_peoplePhotos release];
    [albumVC release];
    [super dealloc];
}

#pragma mark - Action

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table View Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{     
    switch (indexPath.section) {
        case 0: {
            return 74;
        }
            
        case 1: {
            return ([[_peopleSetting objectForKey:@"status"] integerValue] == 1 ? 44 : 0);
        }
        case 2: {
            return 44;
        }
        case 3: {
            return 44;
        }                   
    }
 
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0: {
            return 1;
        }

        case 1: {
            return 1;
        }
        case 2: {
            return 1;
        }
        case 3: {
            return [_publicInfomation count];
        }                   
    }
    
    return 0;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    switch (indexPath.section) {
        case 0: {            
            cell = [self createFromNibForCell1];
            UIImage *avatar = [_peopleInfo objectForKey:@"avatar"];
            avatar = avatar ? avatar : [UIImage imageNamed:@"photo-frame"];
            
            [[cell buttonWithTag:1] setBackgroundImage:avatar 
                                              forState:UIControlStateNormal];
            [cell titleTextWithTag:2].text = [_peopleInfo objectForKey:@"name"];
            [cell titleTextWithTag:3].text = [JGoUtility stringFromDate4:[_peopleInfo objectForKey:@"dob"]];
            [cell titleTextWithTag:4].text = [_peopleInfo objectForKey:@"university"];
            break;
        }
            
        case 1: {
            cell = [self createFromNibForCell2];            
            [cell titleTextWithTag:2].text = [JGoUtility stringForRelationshipStatus:
                                              [[_peopleInfo objectForKey:@"relationship_status"] intValue]];
            [cell setHidden:([[_peopleSetting objectForKey:@"status"] integerValue] == 0)];
            
            break;
        }
        case 2: {
            cell = [self createFromNibForCell3];
            [cell titleTextWithTag:2].text = [NSString stringWithFormat:@"%d",[_peoplePhotos count]];
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            break;
        }
        case 3: {
            cell = [self createFromNibForCell4];
            
            NSDictionary *aInfomation = [_publicInfomation objectAtIndex:indexPath.row];
            NSString *key = [[aInfomation allKeys] objectAtIndex:0];
            NSString *value = [aInfomation objectForKey:key];
            
            [cell titleTextWithTag:1].text = key;
            [cell titleTextWithTag:2].text = value;
            [self sizeToFitForCell:cell];
            break;

        }                   
    }

    if (indexPath.section == 0) {
        cell.backgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else {
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 2) {        
        
        albumVC.navController = self.navigationController;
        albumVC.photos = (id)_peoplePhotos;
        albumVC.type = AlbumForPeople;
        
        [self.navigationController pushViewController:albumVC animated:YES];
    }
}

#pragma mark - DelayMethod

- (void)delayLoadPeoplePhoto:(MBProgressHUD*)progess
{         
    NSError *error = nil;
    NSArray *photos = nil;   
    
    photos = [JGoAPI getPhotoWithUserId:[_peopleInfo objectForKey:@"user_id"] error:&error];

    if (!error) {
        _peoplePhotos = [photos retain];
        [self.tableView reloadData];
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
        
    [progess hide:YES];
}

@end
